package com.lagou.nettyspringboot.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket服务端业务处理器
 */
@Component
@ChannelHandler.Sharable //交给spring管理所以是单例,添加注解通道共享
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * 模拟聊天室,将所有在线的channel放入
     */
    public static Set<Channel> channelSet = new CopyOnWriteArraySet<>();


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String msg = textWebSocketFrame.text();
        System.out.println("msg: " + msg);
        Channel channel = channelHandlerContext.channel();
        //给所有聊天室里的人发消息
        for (Channel channel1 : channelSet) {
            //排除自己
            if (channel1 != channel) {
                channel1.writeAndFlush(new TextWebSocketFrame(msg));
            }
        }
    }

    /**
     * 通道就绪事件 - 上线
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //加入聊天室
        channelSet.add(channel);
        System.out.println("[用户]：" + channel.remoteAddress().toString() + "上线。。。");
    }


    /**
     * 通道未就绪事件 - 下线
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //移出聊天室
        channelSet.remove(channel);
        System.out.println("[用户]：" + channel.remoteAddress().toString() + "下线啦。。。");
    }

    /**
     * 通道异常事件
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        Channel channel = ctx.channel();
        //移出聊天室
        channelSet.remove(channel);
        System.out.println("[用户]：" + channel.remoteAddress().toString() + "出异常啦。。。");
    }
}
